package Jealous;
 
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
import javax.microedition.location.Coordinates;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.StringItem;
import javax.microedition.location.*;
import javax.microedition.io.file.*;
import javax.microedition.io.*; 
import java.io.*;




public class Jealous extends MIDlet implements CommandListener, ItemCommandListener, Runnable {

	//////////////////////////////
	private Form 		myForm = new Form("LOCATION");;	
	 private Criteria criteria;	 
	 private Coordinates coordinates=null;
	 private LocationProvider lp = null;
			Orientation orientation;
		    Thread t;
		    /////////////////////////////////////////////////////////////////////////////////////
			private Command exitCommandIntro =  new Command("Exit", Command.EXIT, 0);
		    private Command cmdMail = new Command("cmdEMail", Command.ITEM, 0);
		    private Command cmdTCP = new Command("cmdTCPC", Command.ITEM, 0);
		    private Command cmdImagePic = new Command("Start", Command.ITEM, 0);
		    ///////////////////////////////////////////////////////////////////////////////////////////
			private StringItem strButtonMail=new StringItem("","OK",Item.BUTTON);
			private StringItem strButtonImage=new StringItem("","START",Item.BUTTON);	//FD 9-10-12
		    private TextField itemEditText= new TextField("Enter E-Mail", "", 30,TextField.EMAILADDR);
		    ///////////////////////////////////////////////////////////////////////////////////////
	        private Display display;
	        private static int _interval = -1;
	        private Alert alert;
	        DatosGPS objDatosGPSLcform= new DatosGPS();
	        //////////////////////////////////////////////////////////////////////////////////////////
			StringItem strLocLat;
			StringItem strLocLon;
			StringItem strSpeed;
			StringItem strBatteryLev;
			boolean bMailCompleto=false;		
		     ///////////////////////////////////////////////////////////////////////////////////////////
			 private Image PrinImage=null;
			 public String strDirImageComienzo="/comienzo3en.png";
				DatosGPS objDatosGPSLoc= new DatosGPS();
			////////////////////////////////////////////////////////////////
				//private String path=System.getProperty("fileconn.dir.private");
				private String path=System.getProperty("fileconn.dir.photos")+"cys/";
				 
				//private String path=System.getProperty("file:///C:/cys/");
				//private String path=System.getProperty("file:///C:/");
				//private String path=System.getProperty("file:///CFCard/");
				//private String path=System.getProperty("file:///SDCard/");
			//	private String path=System.getProperty("file:///MemoryStick/");
				/*fileconn.dir.photos
				fileconn.dir.videos
				fileconn.dir.tones
				fileconn.dir.memorycard
				fileconn.dir.private
				*/
				private String strNameFile="cysgps.txt";
				String strMailGlobal=null;
            	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////		
 public class DatosGPS {
	    	
    public double dbLatitudCoordinates=0;      			 
    public  double dbLongitudCoordinates=0;      	
    public  float altitud=0;      	
    public  float course=0;      			 
    public  float speed=0;
   	public String strLatitud=null;
   	public String strLongitud=null;   	
   	public String imei=null;   	
   	public String strEmail=null;
   	public String strBatLev=null;
}
	void voPantallaBienvenida()
	{      

    
		System.out.println("[voPantallaBienvenida] HOLA BIENVENIDA\n");
	    //try {
	    	try {
	    		
	    		//System.out.println("IMAGEN: "+strDirImageComienzo);
				PrinImage = Image.createImage(strDirImageComienzo);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("ERROR: No paso imagen"+e+"\n");
			}
	    	//addCommand(cmdImg);
	    //setAccountImage=Image.createImage("/res/b_setAccount.gif");
		//byte[] ImagePrin = new byte[100];
	    	//PrinImage.getGraphics();
	    	
		myForm.deleteAll();
		myForm.setTitle("Hello To Jealous");
		//myForm.addCommand(cmdImg);
		myForm.append(PrinImage);	
		
		strButtonImage.setDefaultCommand(cmdImagePic);
    	strButtonImage.setItemCommandListener(this);
		// myForm.addCommand(exitCommandIntro);
		myForm.append(strButtonImage);
		
		myForm.setCommandListener(this);
		//System.out.println("Adjunte imagen\n");
		display = Display.getDisplay(this);
        display.setCurrent(myForm);	
		//PrinImage=Image.createImage(ImagePrin,0,ImagePrin.length);
	}
			       
    public Jealous() {    	
    	//System.out.println("HEALLO TO JEALOUS");
    	voPantallaBienvenida();
    	
    }
    
    void voPantallaMail()
    {
            	
    	//myForm.removeCommand(exitCommandIntro);
  	    itemEditText.setString(null);    	
    	System.out.println("Jealus");
    	myForm.deleteAll();
    	myForm.setTitle("Hello To Jealous");  
    	//itemEditText.setItemCommandListener(cmdMailListener);
       	myForm.append(itemEditText);
       	strButtonMail.setDefaultCommand(cmdMail);
		strButtonMail.setItemCommandListener(this);
		// myForm.addCommand(exitCommandIntro);
		myForm.append(strButtonMail);
		myForm.setCommandListener(this);
		
		System.out.println("Constructor OK");
		this.startApp();
    }

    public void voFormStarting()
    {  
    	myForm.removeCommand(exitCommandIntro);
    	myForm.removeCommand(cmdMail);
    	myForm.deleteAll();		
       	myForm.setTitle("Hello To Jealous");  
    	myForm.append( new StringItem("Starting...","Iniciando...\n" ));
    	myForm.append( new StringItem("Searching for satelites...\n","Buscando satelites...\n" ));
    	// myForm.addCommand(exitCommandIntro);
 		// myForm.setCommandListener(this);
 		
 		display.setCurrent(myForm);
    }

    ///////////////////////////////////////////////////////// /////////////////////////////////////////////////////////  
    public void commandAction(Command c, Item item) {
    	System.out.println("[commandAction] CommandItem");
            if (c == cmdMail){           	
            	System.out.println("[commandAction] PATH: "+path+"\n");
            	//showConfirmation("PATH: ",path);		//DEBUG
            	
            	saveFile(path, strNameFile);
            	
            	strMailGlobal=itemEditText.getString();
            	
            	t = new Thread(this);	//FUNCION RUN
           	 	t.start();
            	
            }
            else if (c == cmdImagePic){
            	System.out.println("[commandAction] ***Boton Image Presionado\n");
            	
            	System.out.println("[commandAction] PATH: "+path+"\n");
            	//showConfirmation("PATH: ",path);		//DEBUG
            	
            	strMailGlobal=ReadFile(path, strNameFile);
            	if(strMailGlobal==null)            	
            	{
            		System.out.println("[commandAction] ***NO EXISTE MAIL\n");
            		voPantallaMail();
            	}else
            	{       		
            		System.out.println("[commandAction] ***YA EXISTE MAIL\n");
            		t = new Thread(this);	//Funcion RUN
               	 	t.start();
            	}
            	
            }else if (c == cmdTCP) {
            	System.out.println("[commandAction] TCP Conection  ok\n");   
            }else
        	{
        		System.out.println("[commandAction] Button not changed\n");	
            	return;
        	}
    }
    public void commandAction(Command command, Displayable displayable) {
    	System.out.println("[commandAction] CommandAction\n");
        if (displayable == myForm) {
        	 if (command == exitCommandIntro) {
             	System.out.println("[commandAction] ExitAction\n");
                 exitMIDlet();
             }
        	/* if(command == cmdImg)
        	 { 
        		 voPantallaMail();
        		 System.out.println("Image Pressed");
        	 }*/
        }
    }
    ///////////////////////////////////////////////////////// /////////////////////////////////////////////////////////    
	public void run() {
		//System.out.println(itemEditText.getString());
		System.out.println("[RUN] MAIL: "+strMailGlobal+"\n");
		//strMailGlobal=itemEditText.getString();
		if((strMailGlobal!="")&&(strMailGlobal!=" ")&&(strMailGlobal!=null))
        {
        	objDatosGPSLoc.imei=System.getProperty("com.nokia.mid.imei");        	
        	objDatosGPSLoc.strEmail=strMailGlobal;
        	System.out.println("[RUN]OK Mail \n");	
        	voFormStarting();
        	bMailCompleto=true;
        	this.GetDatosGPS();
        }else
        {
        	System.out.println("[RUN] Mail Fallo");	
        	return;
        }
	}	
    public void startApp() {      
    	try {
    		display = Display.getDisplay(this);  
            display.setCurrent(myForm);	 
            System.out.println("[startApp] Display OK\n");
  	       //////////////////////////////////////////////////////////////////////////
    		//this.GetDatosGPS();    		
        	
    		try{Thread.currentThread();
    		Thread.sleep(1);
            } catch(Exception e){}
        	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("[startApp] Exception");	//DEBUG
			e.printStackTrace();
		}
    }
    ////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
   public Form myFormul(DatosGPS objCDatosGPS)  
   {
	   String strFormSpeed;
	   //System.out.println("[myFormul] MyForm\n"); //DEBUG
	   //myForm.delete(0);   
	   
	   myForm.deleteAll();
	   myForm.removeCommand(exitCommandIntro);
	   myForm.setTitle("Hello To Jealous");
	    
	   strFormSpeed=Float.toString(objCDatosGPS.speed);
	   
	    strLocLat= new StringItem("","\nLatitud: \n" + objCDatosGPS.dbLatitudCoordinates );
	    strLocLon= new StringItem("", "\nLongitud: \n" + objCDatosGPS.dbLongitudCoordinates);
	    strSpeed= new StringItem("", "\nSpeed: \n" + strFormSpeed);
	    strBatteryLev= new StringItem("", "\nBattery: \n" + objCDatosGPS.strBatLev);
	    
	    strLocLat.setLayout(Item.LAYOUT_LEFT);
	    strLocLon.setLayout(Item.LAYOUT_LEFT);
	    strSpeed.setLayout(Item.LAYOUT_LEFT);
	    strBatteryLev.setLayout(Item.LAYOUT_LEFT);
	    myForm.append(strLocLat );   
	    myForm.append(strLocLon );
	    myForm.append(strSpeed ); 
	    myForm.append(strBatteryLev );
	    myForm.append("\n" );
      return myForm;
	   
   }
   ////////////////////////////////////////////////////////////////////////////////////////////////
   public void saveFile(String path, String name) {
       try {
    	   FileConnection fconn;
    	   String url = path + name;
    	   //System.getProperty("fileconn.dir.private");
         //  String url= System.getProperty("file:///C:/") + name;
           String string = itemEditText.getString();
           string= string+";";
           
           byte data[] = string.getBytes();
           ///REVISO DIRECTORIO
           
           //fconn = (FileConnection)Connector.open(System.getProperty("file:///C:/cys"), Connector.READ_WRITE);
           //fconn = (FileConnection)Connector.open("file:///C:/cys/", Connector.READ_WRITE);
           fconn = (FileConnection)Connector.open(path, Connector.READ_WRITE);
           if (!fconn.exists()) {
               fconn.mkdir();
           }   
           fconn.close();
           
           ///REVISO FILE
           fconn = (FileConnection)Connector.open(url, Connector.READ_WRITE);
          // fconn = (FileConnection)Connector.open("file:///C:/cys/"+name, Connector.READ_WRITE);
           if (!fconn.exists()) {
               fconn.create();
           }
           else{
        	   
        	   //fconn.delete();
        	  // fconn.create();
           }
           OutputStream ops = fconn.openOutputStream();
           ops.write(data);
           ops.close();
           fconn.close();
       }
       catch (IOException ioe) {
           System.out.println("[saveFile]IOException: "+ioe.getMessage());
       }
       catch (SecurityException se) {
           System.out.println("[saveFile]Security exception:" + se.getMessage());
       }
   } 
   public String ReadFile(String path, String name) {
       String url = path + name;
       //String url= System.getProperty("file:///C:/") + name;
       
       byte[] b = new byte[60];
       String smail = null;
	   try 
	   {
		   FileConnection fconn = (FileConnection)Connector.open(url, Connector.READ);
           //FileConnection fconn = (FileConnection)Connector.open("file:///cys/", Connector.READ);
		   //showConfirmation("PATH OPENED: ",url);		//DEBUG
           if (fconn.exists()) {                              
              System.out.println("[ReadFile] EXISTE File\n");
               InputStream is = fconn.openInputStream();
               is.read(b);
               is.close();    	
               fconn.close();
           }else
           {
        	   System.out.println("[ReadFile] No existe File");
        	   //showConfirmation("PATH: ",path);		//DEBUG
        	   return null;
        	   
           }
       }
       catch (IOException ioe) {
           System.out.println("[ReadFile]IOException: "+ioe.getMessage()+"\n");
       }
       catch (SecurityException se) {
           System.out.println("[ReadFile]Security exception:" + se.getMessage()+"\n");
       }

       int x=0;
	   while(b[x]!=';')
	   {
		 
		   x++;
		   
	   }	   
	   byte[] byEmail = new byte[x];
	   System.arraycopy(b,0,byEmail,0,x);
	   
	   smail = new String(byEmail);
	   
	   System.out.println("[ReadFile] MAIL LEIDO: " + smail+"\n");
	return smail;
	
   } 
   ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	public boolean GetDatosGPS() 
    {		     
			System.out.println("GetDatos");
    	 //////////////////*******************GPS*************************//////////////////////  
				criteria = new Criteria();
			    criteria.setCostAllowed(false);	  
			    System.out.println("SET COST CRITERIA");
			         
    			try {
    				/////////////////////////////////GPS
    				lp = LocationProvider.getInstance(criteria);    				
    			} catch (LocationException e) {
    				e.printStackTrace();
    			} 
    			try {    				            
    				lp.setLocationListener(new LocationListenerImpl(), _interval, -1, -1);    				
      	    	     System.out.println("setLocationListener");

    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}	
    	      return true;

    }
    
    public class LocationListenerImpl implements LocationListener 
    {
    	Form miFormu;
    	  
		public void locationUpdated(LocationProvider provider, Location location) {
			// TODO Auto-generated method stub
			 System.out.println("[LocationListenerImpl]LocationUpdated \n");
			try
			{    			
				//GPS
				/*   int[] methods = {(Location.MTA_ASSISTED  | Location.MTE_SATELLITE | Location.MTY_TERMINALBASED)};			    
			   
					try {
						lp = LocationUtil.getLocationProvider(methods, null);
					} catch (LocationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}	
					showConfirmation("Location","GPS");				
					*///location=null;
				if((location!=null)&&(location.isValid()))
				{
					 //System.out.println("[LocationListenerImpl] ValidGPS \n");					 
					coordinates = location.getQualifiedCoordinates();						
					//voGuardarDatosGPS(coordinates,location);
					objDatosGPSLoc.dbLatitudCoordinates = coordinates.getLatitude();
					objDatosGPSLoc.dbLongitudCoordinates = coordinates.getLongitude();
					 objDatosGPSLoc.course = location.getCourse();
					 objDatosGPSLoc.speed = location.getSpeed();
					 objDatosGPSLoc.altitud=location.getQualifiedCoordinates().getAltitude();
					 
					 //String strBatLevel=batteryLevel();	//VERIFICAR MODIFICAR SI ES NECESARIO IN EL %					 
					 //strBatLevel=strBatLevel.substring(0, strBatLevel.length()-1);					 
					 //objDatosGPSLoc.strBatLev=strBatLevel;
					 objDatosGPSLoc.strBatLev=batteryLevel();
					 //System.out.println("BATERIA :" +objDatosGPSLoc.strBatLev);
					 
					 //objDatosGPSLoc.strBatLev=String.valueOf(charbat);
				
					 
					 objDatosGPSLcform=objDatosGPSLoc;				 
		    		 miFormu=myFormul(objDatosGPSLcform);
		    		 EnviarDatosTCP(objDatosGPSLcform);
		             display.setCurrent(miFormu);	
		             System.out.println("LocationUpdatedGPS");
				}else
				{
					////////////////////////////////GSM
					/*
					 int[] methodsCELL = {(Location.MTA_ASSISTED | Location.MTE_CELLID | Location.MTE_SHORTRANGE | Location.MTY_NETWORKBASED)};
						try {
							lpGSM = LocationUtil.getLocationProvider(methodsCELL, null);
							Location locationGSM = null;
							try {
								locationGSM = lpGSM.getLocation(50000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
					        coordinates=locationGSM.getQualifiedCoordinates();					        
					        System.out.println("ValidGSM");					 													
							voGuardarDatosGPS(coordinates,locationGSM);					 
							 objDatosGPSLcform=objDatosGPSLoc;				 
				    		 miFormu=myFormul(objDatosGPSLcform);
				    		 EnviarDatosTCP();
				             display.setCurrent(miFormu);	
					        System.out.println("LocationUpdatedGSM");
						} catch (LocationException e) {
							e.printStackTrace();
						}	
					 	*/
				}
			          
			}catch(RuntimeException re)
			{
				//showConfirmation("Location","notChange");	//DEBUG
			 }
			finally
			{
				try {
					location.wait(1);
					provider.wait(1);
					System.out.println("[LocationListenerImpl] LocationWait \n");
					
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			 
		}

		public void providerStateChanged(LocationProvider provider, int newState) {
			//showConfirmation("Provider","Change");	//DEBUG
            if(newState == LocationProvider.TEMPORARILY_UNAVAILABLE)
            {
                provider.reset();
            }
            //display.setState(newState);
		}
    }
    private static String batteryLevel() {
        String level = System.getProperty("com.nokia.mid.batterylevel");
        
        System.out.println("[batteryLevel] Level 1: "+level);
        if (null == level) {
            level = System.getProperty("batterylevel");
            System.out.println("[batteryLevel] Level 2: "+level);    
        }
        return level;
    }
	public void voGuardarDatosGPS(Coordinates coordinates2,Location location2)
	{
	
	  /*	objDatosGPSLoc.dbLatitudCoordinates = coordinates2.getLatitude();
		objDatosGPSLoc.dbLongitudCoordinates = coordinates2.getLongitude();
		 objDatosGPSLoc.course = location2.getCourse();
		 objDatosGPSLoc.speed = location2.getSpeed();
		 objDatosGPSLoc.altitud=location2.getQualifiedCoordinates().getAltitude();
		 objDatosGPSLoc.altitud=location2.getQualifiedCoordinates().getAltitude();
		 objDatosGPSLoc.strBatLev=batteryLevel();
		 
	 System.out.println("Latitud: " + objDatosGPSLoc.dbLatitudCoordinates);
	 System.out.println("Longitud: " + objDatosGPSLoc.dbLongitudCoordinates);
	 System.out.println("Speed: " + objDatosGPSLoc.speed);
	 System.out.println("Course: " + objDatosGPSLoc.course);
	 System.out.println("Altitud: " + objDatosGPSLoc.altitud);
	 System.out.println("Email: " + objDatosGPSLoc.strEmail);
	 System.out.println("Imei: " + objDatosGPSLoc.imei);
	 System.out.println("Battery: " + batteryLevel());
	// showConfirmation("LATITUD",objDatosGPSLoc.strLatitud);		//DEBUG
	 //showConfirmation("LONGITUD",objDatosGPSLoc.strLongitud);	//DEBUG
	 */
	}
	
    public void EnviarDatosTCP(DatosGPS objDatosGPSLcform1)
    {
    	 TCPConnectionHandler objConection = new TCPConnectionHandler();
    	 
			 
			try {
				objConection.SocketListenerFD(objDatosGPSLcform1);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    }
    
    // Your MIDlet should not call pauseApp(), only system will call this life-cycle method
    public void pauseApp() {
    	System.out.println("[pauseApp] Pause APP");
    }
 
    // Your MIDlet should not call destroyApp(), only system will call this life-cycle method    
    public void destroyApp(boolean unconditional) {
    	System.out.println("[destroyApp] Destroy APP");
    }
 
    public void exitMIDlet() {
    	System.out.println("[exitMIDlet] Exit MID");
    	
        display.setCurrent(null);
        notifyDestroyed();
    }
 
   /* private void closeAlert() {
    	Form miform = null;
        Display.getDisplay(this).setCurrent(miform);
        alert = null;        
    }*/
    protected void showConfirmation(String title, String text) {
        alert = new Alert(title, text, null, AlertType.CONFIRMATION);
        Display.getDisplay(this).setCurrent(alert);
      /*  try {
			wait(2);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
    }

	
    /*
                println("RamFree: "   + System.getProperty("com.nokia.memoryramfree"));
                println("Network: "   + System.getProperty("com.nokia.mid.networkid"));
                //println("Avaliable: " + System.getProperty("com.nokia.mid.networkavailability"));
                //println("Status: "    + System.getProperty("com.nokia.mid.networkstatus"));
                println("Signal: "    + System.getProperty("com.nokia.mid.networksignal"));
                println("Indicator: " + System.getProperty("com.nokia.canvas.net.indicator.location"));
                //println("SellId: "    + System.getProperty("com.nokia.mid.cellid"));
                println("Point: "     + System.getProperty("com.nokia.network.access"));

                println("Battery: " + batteryLevel());
                println("Params: "     + System.getProperty("com.nokia.mid.cmdline"));
     * */
    
} 